//
//  Http.swift
//  foreign_swift
//
//  Created by hdr on 15-4-11.
//  Copyright (c) 2015年 hdr. All rights reserved.
//

import Foundation
import Alamofire

typealias HttpSuccessHandler = JSON->Void
typealias HttpFailureHandler = (code:Int,msg:String?)->Void

class Http {
    
    static var session_key:String?
    
    private var successHanlder:HttpSuccessHandler?
    private var url:String!
    private var failureHanlder:HttpFailureHandler?
    private var parameters:Dictionary<String,AnyObject>?
    private var alertVC:UIAlertController?
  
    static func  setPublicParameters(inout parameters: Dictionary<String,AnyObject>?){
        parameters?["app_revision"] = "1.0"
        parameters?["app_id"]="Yolanda_Bodyfat"
        parameters?["platform"]="iphone"
        if  session_key != ""{
            parameters?["terminal_user_session_key"] = session_key
        }
    }
    
    private static func send(method:Alamofire.Method,parameterEncoding:ParameterEncoding,url:String,var parameters: Dictionary<String,AnyObject>?)->Http{
        let http = Http()
        
        http.parameters = parameters
        http.url = url
        
        setPublicParameters(&parameters)
        Alamofire.request(method, Urls.baseUrl + url, parameters: parameters, encoding: parameterEncoding).response({(request:NSURLRequest, response:NSHTTPURLResponse?, data:AnyObject?, error:NSError?) -> Void in
            if let vc = http.alertVC{
                println("取消进度框")
                vc.dismissViewControllerAnimated(false, completion: {
                    self.handle(http,data as? NSData,error)
                })
            }else{
                self.handle(http,data as? NSData,error)
            }
            
        })
        return http
    }
    
    static func handle(http:Http,_ data:NSData?,_ error:NSError?){
        if let error = error ,onFailure = http.failureHanlder{
            
        }else if let data = data{
            let json = JSON(data:data)
            if json["status_code"].numberValue == 20000 {
                if let onSuccess = http.successHanlder {
                    onSuccess(json)
                }
            }else {
                println("url:\(http.url) 请求错误")
                println(json)
                if let onFailure = http.failureHanlder {
                    var code = json["status_code"].numberValue?.integerValue
                    var msg  = json["status_message"].stringValue
                    onFailure(code: code!,msg: msg)
                }
            }
        }

    }

    static func post(url:String,var parameters: Dictionary<String,AnyObject> = [String:AnyObject]())->Http{
        return send(.POST, parameterEncoding: ParameterEncoding.JSON, url: url, parameters: parameters)
    }
    static func put(url:String,var parameters: Dictionary<String,AnyObject> = [String:AnyObject]())->Http{
        return send(.PUT, parameterEncoding: ParameterEncoding.JSON, url: url, parameters: parameters)
    }
    
    static func get(url:String,var parameters: Dictionary<String,AnyObject> = [String:AnyObject]())->Http{
        return send(.GET, parameterEncoding: ParameterEncoding.URL, url: url, parameters: parameters)
    }
    
    func success(onSuccess:HttpSuccessHandler) -> Http{
        self.successHanlder = onSuccess
        return self
    }
    
    func failure(onFailure:HttpFailureHandler) -> Http{
        self.failureHanlder = onFailure
        return self
    }
    func showProgress(vc:UIViewController) -> Http{

        self.alertVC = Alter.showLoading(vc)
        return self
    }

    
}